package com.example.administrator.wallet.view.activity.mine.Personal;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.AddProceedBean;
import com.example.administrator.wallet.model.bean.TokenBean;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.FileUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.mine.Personal.ChangNumber.ChangNumberActivity;
import com.example.administrator.wallet.view.activity.mine.Personal.ChangNumber.PhoneNumberActivity;
import com.example.administrator.wallet.view.activity.mine.Personal.RealAuthentication.HasRealAuthenticationAcitivity;
import com.example.administrator.wallet.view.activity.mine.Personal.RealAuthentication.RealAuthenticationAcitivity;
import com.example.administrator.wallet.view.activity.mine.Personal.ReceiptInformation.ReceiptInformationActivity;
import com.google.gson.Gson;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import cn.finalteam.okhttpfinal.RequestParams;
import de.hdodenhof.circleimageview.CircleImageView;
import mvp.presenter.HeaderPresenter;
import mvp.view.IHeaderView;
import okhttp3.Headers;

import static com.example.administrator.wallet.R.id.rl_bankcodes;
import static com.example.administrator.wallet.view.fragment.mine.MineFragment.getHttpBitmap;

public class PersonalCentreActivity extends AppCompatActivity implements IHeaderView {
    private ImageButton mIb_back;
    private TextView mV_title;
    private TextView mTv_photo;
    private TextView mEt_name;
    private TextView tv_GoToTheCertification;
    private View view;
    private RelativeLayout activity_main, mRl_head, mRl_name, mRl_phone, mRl_real, mRl_bankcodes;
    private HeaderPresenter headerPresenter;
    private String mFilePath;
    private String mFileName;
    private String mPDFPath;
    private static final int MSG_TAKE_PHOTO = 1;
    private CircleImageView mClv_head;
    private TokenBean tokenBean;
    private String token = "";
    private String photo = "";
    public static File img;//头像File
    final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
    private String head;
    private static Bitmap bitmap;
    private Button bt;
    private String NickName;
    int verifiedstatus = 0;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private AddProceedBean addProceedBean;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_centre);



        int permission = ActivityCompat.checkSelfPermission(PersonalCentreActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    PersonalCentreActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }

        setStatuColor();


        mIb_back = (ImageButton) findViewById(R.id.finish_img);
        mV_title = (TextView) findViewById(R.id.view_title);
        activity_main = (RelativeLayout) findViewById(R.id.activity_main);
        mRl_head = (RelativeLayout) findViewById(R.id.rl_head);
        mRl_name = (RelativeLayout) findViewById(R.id.rl_name);
        mRl_phone = (RelativeLayout) findViewById(R.id.rl_phone);
        mRl_real = (RelativeLayout) findViewById(R.id.rl_real);
        mRl_bankcodes = (RelativeLayout) findViewById(rl_bankcodes);
        mClv_head = (CircleImageView) findViewById(R.id.clv_head);
        mEt_name = (TextView) findViewById(R.id.et_name);
        mTv_photo = (TextView) findViewById(R.id.tv_photo);
        tv_GoToTheCertification = (TextView) findViewById(R.id.tv_GoToTheCertification);

        NickName = mEt_name.getText().toString();



        final Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        mClv_head.setImageBitmap(bitmap);
                        break;
                }
            }
        };
        reqequestManager.httpPost(Api.BaseUrl + Api.User_Information, Api.getUserInformation(SharedPrefsUtil.getValue(PersonalCentreActivity.this, "wallet", "token", ""), ""), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Gson gson = new Gson();
                tokenBean = gson.fromJson(Response, TokenBean.class);
                String name = tokenBean.getData().getNickname();
                head = tokenBean.getData().getHead_portrait();
                photo = tokenBean.getData().getMobile_phone();
                verifiedstatus = tokenBean.getData().getVerified_status();

                tv_GoToTheCertification.setText(tokenBean.getData().getVerified_status_msg().toString());
                mEt_name.setText(name);
                mTv_photo.setText(photo);
                // 显示
                new Thread() {
                    public void run() {
                        bitmap = getHttpBitmap(head);
                        Message msg = handler.obtainMessage();
                        msg.obj = bitmap;
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                }.start();
            }

            @Override
            public void onFailure(String error) {
            }
        });

        if (verifiedstatus != 1){
            //不用弹出对话框
        }else{
            //弹出未实名认证对话框
//            initPw();
        }
        mClv_head.setImageDrawable(Drawable.createFromPath(head));
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        mIb_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.PersonalCenter);

        headerPresenter = new HeaderPresenter(this, this);
        FileUtils.init();
        mFilePath = FileUtils.getFileDir() + File.separator;
        mPDFPath = FileUtils.getFileDir() + File.separator + "abc.pdf";

        mRl_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initCurrency();
            }
        });
        mRl_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),ChangeNameActivity.class));
                finish();
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });

        mRl_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(photo)) {
                    Intent i = new Intent(new Intent(PersonalCentreActivity.this, ChangNumberActivity.class));
                    i.putExtra("num", photo);
                    i.putExtra("context",1);
                    startActivityForResult(i, 0);
                    finish();
                    overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);

                } else {
                    startActivity(new Intent(PersonalCentreActivity.this, PhoneNumberActivity.class));
                    finish();
                    overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);

                }

            }
        });

        //实名认证
        mRl_real.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (verifiedstatus == 0){
                    //未认证
                    startActivity(new Intent(PersonalCentreActivity.this, RealAuthenticationAcitivity.class));
                }else{
                    //审核中,已认证
                    startActivity(new Intent(PersonalCentreActivity.this, HasRealAuthenticationAcitivity.class));
                }
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });
        mRl_bankcodes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonalCentreActivity.this, ReceiptInformationActivity.class));
                overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
            }
        });
        mIb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);

    }

    private void initPw() {
        view = View.inflate(this, R.layout.popup_personal, null);
        final Button submit = (Button) view.findViewById(R.id.submit);
        final ImageView iv_close = (ImageView) view.findViewById(R.id.ib_close);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(activity_main, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(PersonalCentreActivity.this, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(PersonalCentreActivity.this, 1.0f);
                    }
                });
                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(PersonalCentreActivity.this, RealAuthenticationAcitivity.class));
                        window.dismiss();
                        overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
                    }
                });
                iv_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
            }
        });

    }

    private void initCurrency() {
                view = View.inflate(this, R.layout.popup_head, null);
                final Button open_camera = (Button) view.findViewById(R.id.open_camera);
                final Button open_photo = (Button) view.findViewById(R.id.open_photo);
                final Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);

                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                        window.setFocusable(true);
                        window.setTouchable(true);
                        window.setOutsideTouchable(true);
                        window.showAtLocation(activity_main, Gravity.CENTER, 0, 0);
                        Log.e("TAG-----", "OK");
                        DimbgUtils.dimBackground(PersonalCentreActivity.this, 0.5f);
                        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                DimbgUtils.dimBackground(PersonalCentreActivity.this, 1.0f);
                            }
                        });
                        open_camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Build.VERSION.SDK_INT >= 23) {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(PersonalCentreActivity.this, Manifest.permission.CAMERA);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(PersonalCentreActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                                window.dismiss();

                                return;
                            } else {

                                headerPresenter.takePhoto(PersonalCentreActivity.this);//调用具体方法
                                window.dismiss();

                            }
                        } else {

                            headerPresenter.takePhoto(PersonalCentreActivity.this);//调用具体方法
                            window.dismiss();

                        }

                        window.dismiss();

                    }
                });
                //相册
                open_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headerPresenter.selectFromAlbum();
                        window.dismiss();
                    }
                });
                bt_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
            }
        });


    }

    @Override
    public void setHeaderBitmap(Bitmap bitmap) {
        mClv_head.setImageBitmap(bitmap);
        File file = headerPresenter.getFile(bitmap);
        OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
        OkHttpFinal.getInstance().init(builder.build());
        RequestParams params = new RequestParams();
        params.addFormDataPart("access_token",SharedPrefsUtil.getValue(PersonalCentreActivity.this, "wallet", "token", ""));
        params.addFormDataPart("nickname",mEt_name.getText().toString());
        params.addFormDataPart("head_portrait",file);
        String path = file.getPath();
        HttpRequest.post(Api.BaseUrl+Api.Info_Update,params,new BaseHttpRequestCallback<AddProceedBean>(){
            @Override
            protected void onSuccess(Headers headers, AddProceedBean addProceedBean) {
                super.onSuccess(headers, addProceedBean);
                if (addProceedBean.getCode() == 200){
                    Toast.makeText(getApplicationContext(),addProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getApplicationContext(),addProceedBean.getCode()+addProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                Toast.makeText(getApplicationContext(),errorCode+msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 点击取消按钮
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case 2:
                Uri uri = data.getData();
                headerPresenter.startPhotoZoom(uri);
                break;
            case 3:
                File file = new File(Environment.getExternalStorageDirectory() + "/" + "iMon.jpg");
                headerPresenter.startPhotoZoom(Uri.fromFile(file));
                break;
            case 4:
                if (data != null) {
                    headerPresenter.setView(data);

                }
                break;
            case MSG_TAKE_PHOTO:
                Log.i("main", "to do");
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case 222:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    headerPresenter.takePhoto(PersonalCentreActivity.this);
                } else {
                    // Permission Denied
                    Toast.makeText(PersonalCentreActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }

    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }

}
